<template>
	<view class="container">
		<!-- <view class="navtitle">购买广告</view> -->
		<view class="buy_one">
			<view class="one_t">
				<view class="t_left"></view>
				<view class="t_right">
					<view>{{form.price}}</view>
				</view>
			</view>
			<view class="one_t">
				<view class="t_left2"></view>
				<view class="t_right">
					<view class="t_botm">价格分析-每分钟刷新</view>
				</view>
			</view>
		</view>
		<view class="buy_tow">
			<button class="mini-btn" type="primary" size="mini" :plain="form.plain==0?false:true" @click="handbtn(0)">天数</button>
			<button class="mini-btn m-l-20" type="primary" size="mini" :plain="form.plain==1?false:true" @click="handbtn(1)">小时</button>
			<button class="mini-btn m-l-20" type="primary" size="mini" :plain="form.plain==2?false:true" @click="handbtn(2)">分钟</button>
			<qiun-data-charts type="tarea" :opts="opts" :chartData="chartData" />
		</view>
		<view class="buy_three">
			<view class="left">
				<view class="l_t">
					<view class="t_one">
						<img src="https://pili-vod.guanxikeji.com/goumai/img/1721376373290.png" alt="">
						<view class="txt">通证数量</view>
					</view>
					<view class="t_two">{{form.confirmation}}</view>
					<view class="t_three">{{form.time}}</view>
				</view>
				<view class="l_b" @click="clickNumber(0)">
					<view class="top"></view>
					<view class="center">通证卖出 ></view>
				</view>
			</view>
			<view class="left">
				<view class="l_t">
					<view class="t_one">
						<img src="https://pili-vod.guanxikeji.com/goumai/img/1721376177897.png" alt="">
						<view class="txt">确权积分</view>
					</view>
					<view class="t_two">{{form.usdt}}</view>
					<view class="t_three">{{form.time}}</view>
				</view>
				<view class="l_b" @click="clickNumber(1)">
					<view class=" top top2"></view>
					<view class="center top2center">积分提U > </view>
				</view>
			</view>
		</view>
		<view class="buy_four">
			<view class="top">
				<view class="left">明细记录</view>
				<view class="right" @click="edittype">
					<view>{{form.istype?'通证获得及卖出明细':'确权值获得及卖出明细'}}</view>
					<img src="https://pili-vod.guanxikeji.com/goumai/img/1721376165072.png" alt="">
				</view>
			</view>
			<view class="listbox" v-if="form.Recordlit.length>0">
				<view class="list" v-for="(it,index) in form.Recordlit" :key="index">
					<view class="left">
						<img src="https://pili-vod.guanxikeji.com/goumai/img/1721376191495.png" alt="">
						<view class="txt">
							<view class="top">
							<view>	{{["买入", "卖出","提U"][it.detailed]}}</view>
							<view class="pric" v-if="it.detailed !== 2">{{it.price.toFixed(6)}}</view>
							
							</view>
							<view class="bom">{{it.CreatedAt}}</view>
						</view>
					</view>
					<view class="right">{{it.money}}</view>
				</view>
			</view>
			<view class="nodata" v-else>暂无数据</view>
		</view>
		<uni-popup ref="inputDialog" type="dialog">
			<view class="dialbg">
				<view class="title">{{['通证卖出','积分提U'][form.popup]}}</view>
				<view class="line"></view>
				<view class="center">
					<input class="uni-input" v-model="form.sellnumber" type="number" placeholder="请输入数量" />
				</view>
				<view class="formb">
					<view class="btn" @click="dialogInputConfirm(form.sellnumber)">· <text>点击确定</text>  ·</view>
				<!-- 	<button  size="mini" type="default" >取消</button>
					<button type="txt" size="mini" >提交</button> -->
				</view>
			</view>
				<view class="clsebox" @click="inputDialog.close()">
					<view class="clse"></view>
				</view>
						<!-- <uni-popup-dialog ref="inputClose"  mode="input" :title="" 
							placeholder="请输入数量" @confirm="dialogInputConfirm">
							</uni-popup-dialog> -->
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance
	} from "vue";
	import {
		onLoad,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";
	const {
		appContext
	} = getCurrentInstance();
	const chartData = ref({})
	let inputDialog = ref()
	let inputClose = ref()
	const form = reactive({
		wallet_type: 0,
		pages:1,
		page: 0,
		size: 10,
		Recordlit: [],
		istype: true,
		confirmation:0,
		usdt:0,
		time:null,
		price:0,
		plain:0,
		popup:0,
		sellnumber:null,
		
	})

	const opts = reactive({
		color: ["#AE45FF","#7252FF"],
		padding: [20,20,0,0],
		enableScroll: false,
		dataLabel:false,
		legend: {},
		
		xAxis: {
			disableGrid: true,
			 boundaryGap: "justify",
		},
		yAxis: {
			disabled: false,
			gridType: "solid",
			dashLength: 2,
			gridColor: "#AE45FF",
			data: [
						
				{
              min: 0,
              max: 80,
							tofix:6,
            }]
		},
		extra: {
			area: {
				type: "curve",
				opacity: 0.2,
				addLine: true,
				width: 2,
				gradient: true,
				activeType: "hollow",

			}
		}
	})
	onLoad((opt) => {
				// uni.setNavigationBarTitle({ title: '' });
				// uni.setNavigationBarColor({ frontColor: '#040217', backgroundColor: '#040217' });
				// let token =opt.token
				// uni.setStorageSync('token',token)
					getData()
				
	})
	onShow(() => {
	
		
	})
	//下拉加载
	onReachBottom(() => {
		getRecords()
	})
	function getData(){
		getRecords() //通证数量和确权值
		getServerData(0)
			
			// 创建一个Date对象，表示当前日期和时间
			let today = new Date();
			
			// 获取年份
			let year = today.getFullYear();
			
			// 获取月份（注意：月份是从0开始的，所以需要加1）
			let month = today.getMonth() + 1;
			
			// 获取日期
			let date = today.getDate();
			form.time = year+'-'+month+'-'+date
	}
	
	function getServerData(number) {
		//number 0 = 天数  1= 小时  
		appContext.config.globalProperties.$request({
			url: `api/prizes/?code=${number}`,
			method: 'GET',
			success: (res) => {
							form.price =	res.data.price.toFixed(6)
							opts.yAxis.data[0].max = parseFloat((res.data.price*1.2).toFixed(4))
							let  serverData = res.data.list.reverse()
								let price = []
								let quotation = [0,0,0,0,0,0,0]
								serverData.forEach((it) => {
									price.push(parseFloat(it.price.toFixed(4)) )
								})
								price.push(parseFloat(serverData[serverData.length-1].price.toFixed(4)))
								price.shift()
								price.pop()
								setTimeout(() => {
									//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
									let res = {
										categories:number==0?getLastSevenDays():number==1?getLastSevenHours():getLastSevenMinutes(),
										series: [
											{
												name: "价格",
												data: price
											},
											// {
											// 	name: "报价",
											// 	data: quotation
											// },
										]
									};
									chartData.value = JSON.parse(JSON.stringify(res));
								}, 500);	
			},
			fail(err) {
		
			}
		})
		
	}
	//时间修改
	function formatDate(data,type){
			 if (type === 0) {
			        data.forEach(item => {
			            item.CreatedAt = new Date(item.CreatedAt).toISOString().split('T')[0].slice(8, 10);
			        });
			    } else if (type === 1) {
			        data.forEach(item => {
								let timedate = item.CreatedAt.split('T')[1].slice(0, 2);
			            item.CreatedAt = timedate.toString().padStart(2, '0')+':00'
			        });
			    } else {
			        throw new Error('Invalid date type');
			    }
			    return data;
		
	}
	//获取历史记录
	function getRecords(blean) {
		if(blean){
			appContext.config.globalProperties.$request({
				url: `api/tokenRecord/?wallet_type=${form.wallet_type}&page=${form.page}&size=${form.size}`,
				method: 'GET',
				success: (res) => {
					form.confirmation = res.data.confirmation.toFixed(2)
					form.usdt = res.data.usdt.toFixed(2)
						form.pages = Math.ceil(res.data.total / form.size)
					form.Recordlit = res.data.data.map((it) => {
						const dateObj = new Date(it.CreatedAt);
						// 获取年份、月份和日期
						const year = dateObj.getFullYear();
						const month = dateObj.getMonth() + 1; // 月份从0开始，所以需要加1
						const day = dateObj.getDate();
						const hours = dateObj.getHours();
						const minutes = dateObj.getMinutes();
						const seconds = dateObj.getSeconds();
						
						// 格式化为年月日格式
						const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ` +
					`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
						it.CreatedAt = formattedDate
						return it
					})
				},
				fail(err) {
			
				}
			})
		}else if (form.page < form.pages) {
			form.page++
		appContext.config.globalProperties.$request({
			url: `api/tokenRecord/?wallet_type=${form.wallet_type}&page=${form.page}&size=${form.size}`,
			method: 'GET',
			success: (res) => {
				form.confirmation = res.data.confirmation.toFixed(2)
				form.usdt = res.data.usdt.toFixed(2)
			let datas = []
			let datalist = []
						datas = res.data.data
					datalist	= [...form.Recordlit, ...res.data.data]
					form.pages = Math.ceil(res.data.total / form.size)
				form.Recordlit = datalist.map((it) => {
					const dateObj = new Date(it.CreatedAt);
					// 获取年份、月份和日期
					const year = dateObj.getFullYear();
					const month = dateObj.getMonth() + 1; // 月份从0开始，所以需要加1
					const day = dateObj.getDate();
					const hours = dateObj.getHours();
					const minutes = dateObj.getMinutes();
					const seconds = dateObj.getSeconds();
				// 格式化为年月日格式
					const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ` +
				`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
					it.CreatedAt = formattedDate
					return it
				})
			},
			fail(err) {

			}
		})
		}
	}
	//修改时间
	function handbtn(number){
					form.plain = number
				getServerData(number)
	}
	//获取最近七天
	function getLastSevenDays() {
	  const days = [];
	  for (let i = -2; i <= 5; i++) {
	    const date = new Date();
	    date.setDate(date.getDate() - i);
	    const year = date.getFullYear();
	    const month = date.getMonth() + 1;
	    const day = date.getDate();
	    // days.push(`${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`);
	    days.unshift(`${day.toString().padStart(2, '0')}`);
			
	  }
		days.pop()
	  return days;
	}
		//获取最近七小时
	function getLastSevenHours() {
	  const hours = [];
	  for (let i = -2; i <= 5; i++) {
	    const date = new Date();
	    date.setHours(date.getHours() - i);
	    const hour = date.getHours();
	    const minute = date.getMinutes();
	    // hours.unshift(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`);
	    hours.unshift(`${hour.toString().padStart(2, '0')}:00`);
	  }
		hours.pop()
	  return hours;
	}
	//获取最近七个时分
	function getLastSevenMinutes() {
	  const hours = [];
	  for (let i = -2; i <= 5; i++) {
	    const date = new Date();
	    date.setMinutes(date.getMinutes() - i * 10);
	    const hour = date.getHours();
	    const minute = date.getMinutes();
	    hours.unshift(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`);
	  }
		hours.pop()
	  return hours;
	}
	//修改记录
	function edittype() {
		if (form.wallet_type == 0) {
			form.wallet_type = 1
		} else if (form.wallet_type == 1) {
			form.wallet_type = 0
		}
		form.istype = !form.istype
		form.page = 1
		form.size = 10
		getRecords(true)

	}
//通证卖出 积分提U
function clickNumber(number){
	form.sellnumber = null
	inputDialog.value.open()
	form.popup = number

}

//确定卖出
function dialogInputConfirm(e){
			
		if(form.popup == 0){
				appContext.config.globalProperties.$request({
					url: 'api/sellToken/',
					method: 'POST',
					data:{
						money:parseInt(e)
					},
					success: (res) => {		
							uni.showToast({
								icon:'none',
								title:res.errmsg
							})
								form.page = 0
								form.pages = 1
								form.size = 10
								form.plain = 0
								getServerData(0)
								getRecords(true)
					},	
					fail(err) {
				
					}
				})
		}else if(form.popup == 1){
			appContext.config.globalProperties.$request({
				url: 'api/cashUsdt/',
				method: 'POST',
				data:{
					money:parseInt(e)
				},
				success: (res) => {		
						uni.showToast({
							icon:'none',
							title:res.errmsg
						})
						form.page = 0
						form.pages = 1
						form.size = 10
						form.plain = 0
					getServerData(0)
					getRecords(true)
				},
				fail(err) {
			
				}
			})
		}
			inputDialog.value.close()
}
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
	}

	.charts-box {
		width: 100%;
		height: 300px;
	}

	.container {
		padding: 20px;

		.navtitle {
			font-weight: 500;
			text-align: left;
			color: #ffffff;
			font-size: 16px;
			font-family: Source Han Sans SC, Source Han Sans SC-Medium;
		}

		.buy_one {
			margin-top: 60rpx;

			.one_t {
				display: flex;
				align-items: center;

				.t_left {
					width: 24rpx;
					height: 24rpx;
					background: linear-gradient(180deg, #ff2ec2, #492780);
					border-radius: 50%;

				}

				.t_left2 {
					width: 24rpx;
					height: 24rpx;
				}

				.t_right {
					font-size: 44rpx;
					font-family: Source Han Sans SC, Source Han Sans SC-Bold;
					font-weight: 700;
					text-align: left;
					color: #000;
					margin-left: 14rpx;
					display: flex;
					align-items: flex-top;

				}
			}

			.t_botm {
				font-size: 24rpx;
				font-family: Source Han Sans SC, Source Han Sans SC-Regular;
				font-weight: 400;
				text-align: left;
				color: #999999;
				margin-top: 12rpx;
			}
		}

		.buy_tow {
			margin-top: 80rpx;
		}

		.buy_three {
			display: flex;
			justify-content: space-between;
			margin-top: 60rpx;

			.left {
				width: 48%;

				.l_t {
					width: 100%;
					height: 196rpx;
					// background-image: url('https://pili-vod.guanxikeji.com/goumai/img/1721376172180.png');
					background-size: 100% 100%;
					background-repeat: no-repeat;
					display: flex;
					overflow: hidden;
					align-items: center;
					flex-direction: column;
					border-radius: 20rpx;
					background-color: #fff;
					.t_one {
						display: flex;
						margin-top: 20rpx;

						img {
							width: 34rpx;
							height: 34rpx;
						}

						.txt {
							opacity: 0.48;
							font-size: 12px;
							color: #000;
							margin-left: 16rpx;
						}
					}

					.t_two {
						font-size: 22px;
						font-family: Source Han Sans SC, Source Han Sans SC-Bold;
						font-weight: 700;
						color: #000;
						margin-top: 20rpx;
						width: 90%;
						text-align: center;
					}

					.t_three {
						opacity: 0.48;
						font-size: 12px;
						font-family: Source Han Sans SC, Source Han Sans SC-Regular;
						font-weight: 400;
						color: #000;
						margin-top: 20rpx;
						word-wrap: break-word;
						text-align: center;
					}

				}

				.l_b {
					width: 100%;
					height: 126rpx;
					// background-image: url('https://pili-vod.guanxikeji.com/goumai/img/1721376186306.png');
					background-size: 100% 100%;
					background-repeat: no-repeat;
					display: flex;
					margin-top: 40rpx;
					align-items: center;
					flex-direction: column;
					background-color: #fff;
					border-radius: 20rpx;
					.top {
						display: flex;
						justify-content: center;
						width: 132rpx;
						height: 8rpx;
						background: #fec743;
						border-radius: 3px;
						box-shadow: 0px 1px 10px 0px #fec743;
					}

					.top2 {
						background: #4d96ff;
					}

					.center {
						font-size: 32rpx;
						font-family: Source Han Sans SC, Source Han Sans SC-Bold;
						font-weight: 700;
						color: #fec743;
						display: flex;
						align-items: center;
						flex: 1;
					}
					.top2center{
						color: #4d96ff;
					}
				}
			}
		}

		.buy_four {
			margin-top: 108rpx;

			.top {
				display: flex;
				justify-content: space-between;

				.left {
					font-size: 22px;
					font-family: Source Han Sans SC, Source Han Sans SC-Bold;
					font-weight: 700;
					color: #000;
				}

				.right {
					display: flex;
					align-items: center;
					font-size: 12px;
					font-family: Source Han Sans SC, Source Han Sans SC-Regular;
					font-weight: 400;
					color: #cc52ff;

					img {
						width: 16rpx;
						height: 10rpx;
						margin-left: 10rpx;
					}
				}
			}

			.listbox {
				margin-top: 60rpx;

				.list {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-bottom: 30rpx;
					border-bottom: 1px solid #3A2E56;

					.left {
						display: flex;
						align-items: center;

						img {
							width: 88rpx;
							height: 88rpx;
						}

						.txt {
							margin-left: 20rpx;

							.top {
								font-size: 14px;
								font-family: Source Han Sans SC, Source Han Sans SC-Bold;
								font-weight: 700;
								text-align: left;
								color: #ffffff;
								display: flex;
								justify-content: flex-start;
								.pric{
											font-size: 12px;
											color: #999999;
											font-weight: 400;
											margin-left: 8rpx;
											display: flex;
											align-items: flex-end;
								}
							}

							.bom {
								margin-top: 6rpx;
								font-size: 12px;
								font-family: Source Han Sans SC, Source Han Sans SC-Regular;
								font-weight: 400;
								text-align: left;
								color: #999999;
							}
						}
					}

					.right {
						font-size: 36rpx;
						font-family: Source Han Sans SC, Source Han Sans SC-Bold;
						font-weight: 700;
						color: #ffffff;
					}
				}

				.list:last-child {
					border-bottom: none;
				}
			}
			.nodata{
				color: #999999;
				display: flex;
				justify-content: center;
				margin-top: 30rpx;
			}
		}

	}
	.m-l-20{
		margin-left: 20rpx;
	}
	// ::v-deep .uni-popup-dialog{
	// 	background-color: #fff !important;
	// }
	.dialbg{
		background-image: url('https://pili-vod.guanxikeji.com/goumai/img/1721462469674.png');
		background-size: 100% 100%;
		background-repeat: no-repeat;
		width: 278px;
		height: 193px;
		padding: 20rpx;
		background: #fff;
		border: 1px solid #625f86;
		border-radius: 27px;

		.title{
				font-size: 20px;
				font-family: Source Han Sans SC, Source Han Sans SC-Bold;
				font-weight: 700;
				text-align: left;
				color: #000;
				display: flex;
				justify-content: center;
				margin-top: 35rpx;
		}
		.line{
			height: 1px;
			opacity: 0.48;
			background-color:  #999;
			margin-top: 35rpx;
		}
		.center{
			display: flex;
			justify-content: center;
			width: 100%;
			margin-top: 35rpx;
			.uni-input{
				display: flex;
				justify-content: center;
				width: 80%;
				color: #000;
				background: #f5f5f5;
				border-radius: 10px;
				height: 100rpx;
				padding: 0px 10px;
				
		}

		}
		.formb{
			margin-top: 35rpx;
			display: flex;
			justify-content: center;
			.btn{
				font-size: 32rpx;
				font-family: Source Han Sans SC, Source Han Sans SC-Medium;
				font-weight: 500;
				color: #000;
				padding-bottom: 5rpx;
				text{
					border-bottom: 1px solid #999;
				}
			}
		}
	}
	.clsebox{
		width: 100%;
		display: flex;
		justify-content: center;
		margin-top: 34rpx;
		.clse{
			
			width: 42px;
			height: 101px;
			background-image: url('https://pili-vod.guanxikeji.com/goumai/img/1721463176152.png');
			background-repeat: no-repeat;
			background-size: 100% 100%;
		}
	}

</style>